﻿
namespace Numbrella.WebClient
{
    using System;
    using System.ServiceModel;
    using System.Windows;
    using System.Windows.Controls;
    using Numbrella.Tracker.WebService;

    public partial class LoginPage : UserControl
    {
        public LoginPage()
        {
            InitializeComponent();
        }

        private void OnLoginButton_Click(object sender, RoutedEventArgs e)
        {
            IAuthorizationService authService =
                new ChannelFactory<IAuthorizationService>("BasicHttpBinding_IAuthorizationService").CreateChannel();

            AsyncCallback asyncCallBack =
                delegate(IAsyncResult result)
                {                    
                    UserToken userToken = authService.EndLogin(result);

                    if (userToken == null)
                    {
                        this.Dispatcher.BeginInvoke(
                            delegate
                                {
                                    usernameBox.Text = string.Empty;
                                    passwordBox.Password = string.Empty;
                                    errorBlock.Text = "Invalid username or password. Try Again.";
                                });

                        return;
                    }

                    this.Dispatcher.BeginInvoke(
                        delegate
                        {
                            App.Current.UserToken = userToken;

                            ((Main)this.Parent).Navigate(new TestPage());
                        });                      
                };            

            authService.BeginLogin(usernameBox.Text, passwordBox.Password, asyncCallBack, authService);
        }
    }
}
